import _axios from 'axios'
import qs from 'qs'
import FormData from 'form-data'
import store from '../store'
import router from '../router'
import { isApp, isIOS, isAndroid } from "./device";
let md5 = require('md5')

let appKey = ''
let appSecret = 'fg67htj5y5657jngfg1g8'
let nonce = Math.random().toString(36).substr(2, 15)
let timeStamp = new Date().getTime()

let req = _axios.create()
// req.defaults.withCredentials = true
req.defaults.headers.post['Content-Type'] = 'application/json'

// req.defaults.headers.common['appKey'] = appKey
// req.defaults.headers.common['nonce'] = nonce
// req.defaults.headers.common['timeStamp'] = timeStamp
// req.defaults.headers.common['signature'] = md5(`appKey=${appKey}&nonce=${nonce}&timeStamp=${timeStamp}&appSecret=${appSecret}`)

req.interceptors.response.use((response) => {
  return response
}, (err) => {
  console.log(`interceptors=== ${err}`)
  if (err && err.response) {
    switch (err.response.status) {
        case 400:
          console.log('请求错误(400)')
          break;
        case 401:
          console.log('未授权，请重新登录(401)')
          againGetAppToken()
          // store.commit('SET_LOGINGO', router.currentRoute.fullPath)
          // router.push({
          //   name: 'Login'
          // })
          break;
        case 403:
          console.log('拒绝访问(403)')
          break;
        case 404:
          console.log('请求出错(404)')
          break;
        case 408:
          console.log('请求超时(408)')
          break;
        case 500:
          console.log('服务器错误(500)')
          break;
        case 501:
          console.log('服务未实现(501)')
          break;
        case 502:
          console.log('网络错误(502)')
          break;
        case 503:
          console.log('服务不可用(503)')
          break;
        case 504:
          console.log('网络超时(504)')
          break;
        case 505:
          console.log('HTTP版本不受支持(505)')
          break;
        default:
          console.log(`连接出错(${err.response.status})!`)
    }
  }
})
function againGetAppToken() {
  // if (isApp()) {
  //   if (isIOS()) {
  //     return window.webkit.messageHandlers.againGetAppToken.postMessage({})
  //   }
  //   if (isAndroid()) {
  //     return window.JsMode.againGetAppToken()
  //   }
  // } else {
    store.commit('SET_LOGINGO', router.currentRoute.fullPath)
    router.push({
      path: '/login'
    })
  // }
}
export const axios = req

export const parseForm = qs.stringify

export function PostForm (url, formData, successCbfn = res => res, failCbfn = res => res) {
  return req.post(url, parseForm(formData))
            .then(res => res.data)
  .then(successCbfn)
  .catch(err => {
    failCbfn(err)
    console.log(`get: ${url}`)
    console.log(err)
  })
}

export function GetWithHeader (url, params, successCbfn = res => res, failCbfn = res => res, headers = {}) {
  let instance = _axios.create()
  instance.defaults.headers.post['Accept'] = 'application/json'
  // alert(`store.state.token:${store.state.token}`)
  instance.defaults.headers.common['Authorization'] = store.state.token

  return instance.get(`${url}?v=${new Date().getTime()}`, {
    params
  }, {headers}).then(res => {
    if (res.data.code === 'nologin') {
      // store.commit('SET_LOGINGO', router.currentRoute.fullPath)
      // router.push({
      //   path: '/login'
      // })
      againGetAppToken()
    } else {
      return res.data
    }
  })
    .then(successCbfn)
    .catch(err => {
      console.log('err: ' + err)
      failCbfn(err)
      console.log(`get: ${url}`)
    })
}

export function PostWithHeader (url, data, successCbfn = res => res, failCbfn = res => res, headers = {}) {
  let instance = _axios.create()
  instance.defaults.headers.post['Accept'] = 'application/json'
  instance.defaults.headers.common['Authorization'] = store.state.token

  return instance.post(url, data, {headers})
    .then(res => {
      if (res.data.code === 'nologin') {
        // store.commit('SET_LOGINGO', router.currentRoute.fullPath)
        // router.push({
        //   path: '/login'
        // })
        againGetAppToken()
      } else {
        return res.data
      }
    })
    .then(successCbfn)
    .catch(err => {
      failCbfn(err)
      // console.log(`get: ${url}`)
      // console.log(err)
    })
}

export function Get (url, params, successCbfn = res => res, failCbfn = res => res, config = {}) {
  return req.get(`${url}?v=${new Date().getTime()}`, {
    params
  }, config).then(res => res.data)
    .then(successCbfn)
    .catch(err => {
      failCbfn(err)
      console.log(`get: ${url}`)
      console.log(err)
    })
}

// 提交
export function Post (url, formData, successCbfn = res => res, failCbfn = res => res, config = {}) {
  let jsonString = ''

  try {
    jsonString = typeof formData === 'string' ? formData : JSON.stringify(formData)
  } catch (err) {
    failCbfn(err)
    console.error('JH: 提交的对象不是可以序列化的。')
    console.warn(err)
  }

  return req.post(url, jsonString, config)
            .then(res => res.data)
            .then(successCbfn)
            .catch(err => {
              failCbfn(err)
              console.log(`postJson: ${url}`)
              console.log(err)
            })
}

// 修改
export function Put (url, formData, successCbfn = res => res, failCbfn = res => res, config = {}) {
  let jsonString = ''

  try {
    jsonString = typeof formData === 'string' ? formData : JSON.stringify(formData)
  } catch (err) {
    failCbfn(err)
    console.error('JH: 提交的对象不是可以序列化的。')
    console.warn(err)
  }

  return req.put(url, jsonString, config)
            .then(res => res.data)
            .then(successCbfn)
            .catch(err => {
              failCbfn(err)
              console.log(`postJson: ${url}`)
              console.log(err)
            })
}

// 删除
export function Delete (url, formData, successCbfn = res => res, failCbfn = res => res, config = {}) {
  let jsonString = ''

  try {
    jsonString = typeof formData === 'string' ? formData : JSON.stringify(formData)
  } catch (err) {
    failCbfn(err)
    console.error('JH: 提交的对象不是可以序列化的。')
    console.warn(err)
  }

  return req.delete(url, jsonString, config)
            .then(res => res.data)
            .then(successCbfn)
            .catch(err => {
              failCbfn(err)
              console.log(`postJson: ${url}`)
              console.log(err)
            })
}

export function PostFile (url, file, successCbfn = res => res, failCbfn = res => res) {
  let instance = _axios.create()
  instance.defaults.withCredentials = true

  let data = new FormData()
  data.append('file', file)
  return instance.post(url, data, {headers: {'Content-Type': 'multipart/form-data'}})
          .then(res => res.data)
          .then(successCbfn)
          .catch(err => {
            failCbfn(err)
            console.log(`post file to url ${url}`)
            console.log(err)
          })
}

export function PostFileWithHeader (url, file, successCbfn = res => res, failCbfn = res => res, headers = {}) {
  let instance = _axios.create()
  instance.defaults.headers.post['Accept'] = 'application/json'
  instance.defaults.headers.common['Authorization'] = headers.Authorization

  let data = new FormData()
  data.append('uploadfile', file)

  return instance.post(
    url,
    data,
    {
      headers: {
        'Content-Type': 'multipart/form-data',
      }
    })
    .then(res => res.data)
    .then(successCbfn)
    .catch(err => {
      failCbfn(err)
      console.log(`post file to url ${url}`)
      console.log(err)
    })
}

export function PostMediaFileWithHeaderMediaId (url, file, mediaid, successCbfn = res => res, failCbfn = res => res, headers = {}) {
  let instance = _axios.create()
  instance.defaults.headers.post['Accept'] = 'application/json'
  instance.defaults.headers.common['Authorization'] = headers.Authorization

  let data = new FormData()
  data.append('uploadfile', file)
  data.append('mediaid', mediaid)

  return instance.post(
    url,
    data,
    {
      headers: {
        'Content-Type': 'multipart/form-data',
      }
    })
    .then(res => res.data)
    .then(successCbfn)
    .catch(err => {
      failCbfn(err)
      console.log(`post file to url ${url}`)
      console.log(err)
    })
}
